<template>
  <div class="qr-code-page">
    <div class="generator-container">
      <h1>彩色二维码生成器</h1>
      
      <el-form :model="form" label-width="100px">
        <el-form-item label="输入内容">
          <el-input 
            v-model="form.content" 
            placeholder="请输入要生成二维码的内容"
            class="content-input"
          />
        </el-form-item>

        <el-form-item label="背景样式">
          <div class="style-options">
            <img 
              v-for="(style, index) in styles" 
              :key="'style-' + index" 
              :src="`/images/QRCode/img/${style}.png`"
              :class="['style-option', { selected: form.background === style }]"
              @click="selectStyle(style)"
              :alt="'样式' + (index + 1)"
            >
          </div>
        </el-form-item>

        <el-form-item>
          <div class="button-group">
            <el-button type="primary" @click="generateQRCode">
              <el-icon><Picture /></el-icon>
              生成二维码
            </el-button>
            <el-button type="success" @click="downloadQRCode" :disabled="!qrGenerated">
              <el-icon><Download /></el-icon>
              下载二维码
            </el-button>
            <el-button @click="clearContent">
              <el-icon><Delete /></el-icon>
              清空
            </el-button>
            <el-button type="warning" @click="goToHomepage">
              <el-icon><Back /></el-icon>
              返回
            </el-button>
          </div>
        </el-form-item>
      </el-form>

      <div class="qr-code-container">
        <canvas id="finalQRCode" width="300" height="300"></canvas>
      </div>

      <div class="notes">
        <h3>帮助说明：</h3>
        <ul>
          <li>支持生成各种彩色二维码</li>
          <li>可以选择多种精美背景样式</li>
          <li>支持文本、网址等内容生成</li>
          <li>生成的二维码可直接下载使用</li>
          <li>建议输入内容不要过长</li>
          <li>所有操作在本地完成，不会上传服务器</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Picture, Download, Delete, Back } from '@element-plus/icons-vue'
import QRCode from 'qrcode'

const router = useRouter()
const qrGenerated = ref(false)

const form = ref({
  content: 'https://example.com/',
  background: 'original'
})

const styles = ref(['original', ...Array.from({length: 71}, (_, i) => (i + 1).toString())])
const svgConfigs = ref({})

const selectStyle = (style) => {
  form.value.background = style
  generateQRCode()
}

const generateQRCode = () => {
  if (!form.value.content.trim()) {
    ElMessage.warning('请输入要生成二维码的内容')
    return
  }

  const tempCanvas = document.createElement('canvas')
  QRCode.toCanvas(tempCanvas, form.value.content, {
    width: 280,
    height: 280,
    margin: 0,
    color: {
      dark: '#000000',
      light: '#ffffff00'  // 透明背景
    }
  }, (error) => {
    if (error) {
      console.error(error)
      ElMessage.error('生成二维码失败，请重试')
    } else {
      if (form.value.background === 'original') {
        displayOriginalQRCode(tempCanvas)
      } else {
        loadSVGBackground(tempCanvas)
      }
      qrGenerated.value = true
    }
  })
}

const displayOriginalQRCode = (qrCanvas) => {
  const finalCanvas = document.getElementById('finalQRCode')
  const ctx = finalCanvas.getContext('2d')
  ctx.clearRect(0, 0, finalCanvas.width, finalCanvas.height)
  ctx.drawImage(qrCanvas, 10, 10, 280, 280)
}

const loadSVGBackground = async (qrCanvas) => {
  if (svgConfigs.value[form.value.background]) {
    combineQRCodeWithBackground(qrCanvas, svgConfigs.value[form.value.background])
  } else {
    try {
      const response = await fetch(`/images/QRCode/svg/${form.value.background}.html`)
      const html = await response.text()
      const parser = new DOMParser()
      const doc = parser.parseFromString(html, 'text/html')
      const svgElement = doc.querySelector('svg')
      const configDiv = doc.querySelector(`div[id^="style"]`)
      
      if (svgElement && configDiv) {
        const config = {
          svgElement: svgElement,
          width: parseFloat(configDiv.dataset.width),
          left: parseFloat(configDiv.dataset.left),
          top: parseFloat(configDiv.dataset.top)
        }
        svgConfigs.value[form.value.background] = config
        combineQRCodeWithBackground(qrCanvas, config)
      } else {
        throw new Error('SVG or config not found')
      }
    } catch (error) {
      console.error('Error loading SVG:', error)
      ElMessage.error('加载背景失败，请重试')
    }
  }
}

const combineQRCodeWithBackground = (qrCanvas, config) => {
  const finalCanvas = document.getElementById('finalQRCode')
  const ctx = finalCanvas.getContext('2d')

  ctx.clearRect(0, 0, finalCanvas.width, finalCanvas.height)

  if (form.value.background === 'original') {
    ctx.drawImage(qrCanvas, 10, 10, 280, 280)
  } else {
    const img = new Image()
    const svgBlob = new Blob([config.svgElement.outerHTML], {type: 'image/svg+xml;charset=utf-8'})
    const url = URL.createObjectURL(svgBlob)

    img.onload = () => {
      ctx.drawImage(img, 0, 0, 300, 300)
      
      const qrWidth = 300 * config.width - 10
      const qrLeft = 300 * config.left + 5
      const qrTop = 300 * config.top + 5
      
      ctx.drawImage(qrCanvas, qrLeft, qrTop, qrWidth, qrWidth)
      URL.revokeObjectURL(url)
    }

    img.src = url
  }
}

const downloadQRCode = () => {
  const canvas = document.getElementById('finalQRCode')
  canvas.toBlob((blob) => {
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    const fileName = form.value.background === 'original' ? 'original.png' : `${form.value.background}.png`
    
    link.download = fileName
    link.href = url
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    ElMessage.success('下载开始')
  }, 'image/png')
}

const clearContent = () => {
  form.value.content = ''
  qrGenerated.value = false
  ElMessage.success('已清空')
}

const goToHomepage = () => {
  router.push('/')
}

onMounted(() => {
  generateQRCode()
})
</script>

<style lang="scss" scoped>
.qr-code-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  overflow-y: auto;

  .generator-container {
    max-width: 800px;
    width: 96%;
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
    padding: 30px;
    box-sizing: border-box;
    margin: 10px auto;

    h1 {
      text-align: center;
      color: #4a5568;
      font-size: 28px;
      margin-bottom: 30px;
      text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
    }

    .el-form {
      .el-form-item {
        margin-bottom: 25px;

        :deep(.el-form-item__label) {
          font-weight: 500;
          color: #4a5568;
          padding-bottom: 8px;
        }

        .content-input {
          :deep(.el-input__inner) {
            font-family: 'Monaco', 'Courier New', monospace;
            font-size: 14px;
            padding: 12px;
            border-radius: 8px;
            
            &:focus {
              border-color: #409EFF;
              box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
            }
          }
        }
      }
    }

    .style-options {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      max-height: 180px;
      overflow-y: auto;
      padding-right: 10px;

      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
      }

      &::-webkit-scrollbar-thumb {
        background: #888;
        border-radius: 3px;

        &:hover {
          background: #555;
        }
      }

      .style-option {
        width: 50px;
        height: 50px;
        border: 2px solid transparent;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s ease;
        flex-shrink: 0;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        &.selected {
          border-color: #409EFF;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }
      }
    }

    .button-group {
      display: flex;
      gap: 15px;
      justify-content: center;
      margin: 20px 0;

      .el-button {
        min-width: 120px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 12px 20px;
        font-size: 14px;
        border-radius: 8px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .el-icon {
          font-size: 16px;
        }
      }
    }

    .qr-code-container {
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 30px 0;

      canvas {
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
    }

    .notes {
      margin-top: 40px;
      padding: 20px;
      background-color: #f0f5ff;
      border-radius: 12px;
      color: #606266;
      text-align: left;

      h3 {
        color: #409EFF;
        margin: 0 0 15px 0;
        font-size: 16px;
        text-align: left;
      }

      ul {
        margin: 0;
        padding-left: 0;
        list-style-type: none;
        text-align: left;

        li {
          margin-bottom: 12px;
          line-height: 1.6;
          position: relative;
          padding-left: 18px;
          text-align: left;

          &:before {
            content: "•";
            color: #409EFF;
            font-size: 18px;
            position: absolute;
            left: 0;
            top: -2px;
          }

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .qr-code-page {
    padding: 10px;

    .generator-container {
      padding: 20px;
      width: 100%;

      h1 {
        font-size: 24px;
        margin-bottom: 20px;
      }

      .button-group {
        flex-direction: column;
        gap: 10px;

        .el-button {
          width: 100%;
          margin: 0;
        }
      }

      .notes {
        padding: 15px;
        margin-top: 30px;

        h3 {
          font-size: 15px;
        }

        ul li {
          font-size: 13px;
          margin-bottom: 8px;
        }
      }
    }
  }
}
</style>
